package com.train.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.train.webadmin.app.service.*;
import com.train.webadmin.app.dao.*;
import com.train.webadmin.app.model.*;
import com.train.common.core.base.dao.BaseDaoMapper;
import com.train.common.core.constant.GlobalDeletedFlag;
import com.train.common.core.object.Tuple2;
import com.train.common.core.object.TokenData;
import com.train.common.core.object.MyRelationParam;
import com.train.common.core.object.CallResult;
import com.train.common.core.base.service.BaseService;
import com.train.common.core.util.MyModelUtil;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 课程论坛数据操作服务类。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Slf4j
@Service("courseForumService")
public class CourseForumServiceImpl extends BaseService<CourseForum, Long> implements CourseForumService {

    @Autowired
    private CourseForumMapper courseForumMapper;
    @Autowired
    private CourseForumService courseForumService;
    @Autowired
    private ClassInfoService classInfoService;
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private TeacherInfoService teacherInfoService;
    @Autowired
    private CourseInfoService courseInfoService;
    @Autowired
    private CourseForumFileMapper courseForumFileMapper;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<CourseForum> mapper() {
        return courseForumMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CourseForum saveNew(CourseForum courseForum) {
        if (courseForum.getPid() != null && courseForum.getPid() != 0) {
            TokenData tokenData = TokenData.takeFromRequest();
            if (tokenData.getDeptId() == 1900427267448770560L) {
                StudentInfo studentInfo = studentInfoService.getStudentInfoByUserId(tokenData.getUserId());
                courseForum.setStudentId(studentInfo.getId());
            } else if (tokenData.getDeptId() == 1900427226025824256L) {
                TeacherInfo teacherInfo = teacherInfoService.getTeacherInfoByUserId(tokenData.getUserId());
                courseForum.setTeacherId(teacherInfo.getId());
            }
        }
        courseForumMapper.insert(this.buildDefaultValue(courseForum));
        if (courseForum.getCourseForumFiles() != null) {
            //插入图片数据
            for (CourseForumFile courseForumFile : courseForum.getCourseForumFiles()) {
                courseForumFile.setForumId(courseForum.getId());
                courseForumFileMapper.insert(this.buildDefaultValue(courseForumFile));
            }
        }
        return courseForum;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<CourseForum> courseForumList) {
        if (CollUtil.isNotEmpty(courseForumList)) {
            courseForumList.forEach(this::buildDefaultValue);
            courseForumMapper.insertList(courseForumList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewOrUpdateBatch(List<CourseForum> courseForumList, List<String> duplicateVerifyColumns, int batchSize) {
        if (CollUtil.isEmpty(courseForumList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = CollUtil.isNotEmpty(duplicateVerifyColumns) ? 100 : 10000;
        }
        int start = 0;
        do {
            int end = Math.min(courseForumList.size(), start + batchSize);
            List<CourseForum> subList = courseForumList.subList(start, end);
            if (CollUtil.isNotEmpty(duplicateVerifyColumns)) {
                Tuple2<List<CourseForum>, List<CourseForum>> t = this.deduceInsertOrUpdateList(subList, duplicateVerifyColumns);
                if (CollUtil.isNotEmpty(t.getFirst())) {
                    t.getFirst().forEach(this::buildDefaultValue);
                    courseForumMapper.insertList(t.getFirst());
                }
                t.getSecond().forEach(data -> courseForumMapper.updateById(data));
            } else {
                courseForumList.forEach(this::buildDefaultValue);
                courseForumMapper.insertList(subList);
            }
            if (end == courseForumList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(CourseForum courseForum, CourseForum originalCourseForum) {
        courseForum.setCreateUserId(originalCourseForum.getCreateUserId());
        courseForum.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        courseForum.setCreateTime(originalCourseForum.getCreateTime());
        courseForum.setUpdateTime(new Date());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<CourseForum> uw = this.createUpdateQueryForNullValue(courseForum, courseForum.getId());
        courseForumFileMapper.deleteByForumId(originalCourseForum.getId());
        for (CourseForumFile courseForumFile : courseForum.getCourseForumFiles()) {
            courseForumFile.setForumId(courseForum.getId());
            courseForumFileMapper.insert(this.buildDefaultValue(courseForumFile));
        }
        return courseForumMapper.update(courseForum, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        return courseForumMapper.deleteById(id) == 1;
    }

    @Override
    public List<CourseForum> getCourseForumList(CourseForum filter, String orderBy) {
        TokenData tokenData = TokenData.takeFromRequest();
        return courseForumMapper.getCourseForumList(filter, orderBy, tokenData.getUserId());
    }

    @Override
    public List<CourseForum> getCourseForumListWithRelation(CourseForum filter, String orderBy) {
        TokenData tokenData = TokenData.takeFromRequest();
        List<CourseForum> resultList = courseForumMapper.getCourseForumList(filter, orderBy, tokenData.getUserId());
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public boolean hasChildren(Long id) {
        CourseForum filter = new CourseForum();
        filter.setPid(id);
        return getCountByFilter(filter) > 0;
    }

    @Override
    public CallResult verifyImportList(List<CourseForum> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "pid")) {
            callResult = verifyImportForDatasourceDict(dataList, "pidDictMap", CourseForum::getPid);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "classId")) {
            callResult = verifyImportForDatasourceDict(dataList, "classIdDictMap", CourseForum::getClassId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "studentId")) {
            callResult = verifyImportForDatasourceDict(dataList, "studentIdDictMap", CourseForum::getStudentId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "teacherId")) {
            callResult = verifyImportForDatasourceDict(dataList, "teacherIdDictMap", CourseForum::getTeacherId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "courseId")) {
            callResult = verifyImportForDatasourceDict(dataList, "courseIdDictMap", CourseForum::getCourseId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(CourseForum courseForum, CourseForum originalCourseForum) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(courseForum, originalCourseForum, CourseForum::getPid)
                && !courseForumService.existId(courseForum.getPid())) {
            return CallResult.error(String.format(errorMessageFormat, "父级id"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(courseForum, originalCourseForum, CourseForum::getClassId)
                && !classInfoService.existId(courseForum.getClassId())) {
            return CallResult.error(String.format(errorMessageFormat, "班级id"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(courseForum, originalCourseForum, CourseForum::getStudentId)
                && !studentInfoService.existId(courseForum.getStudentId())) {
            return CallResult.error(String.format(errorMessageFormat, "学生id"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(courseForum, originalCourseForum, CourseForum::getTeacherId)
                && !teacherInfoService.existId(courseForum.getTeacherId())) {
            return CallResult.error(String.format(errorMessageFormat, "老师id"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(courseForum, originalCourseForum, CourseForum::getCourseId)
                && !courseInfoService.existId(courseForum.getCourseId())) {
            return CallResult.error(String.format(errorMessageFormat, "课程id"));
        }
        return CallResult.ok();
    }

    private CourseForum buildDefaultValue(CourseForum courseForum) {
        TokenData tokenData = TokenData.takeFromRequest();
        courseForum.setCreateUserId(tokenData.getUserId());
        courseForum.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        courseForum.setCreateTime(now);
        courseForum.setUpdateTime(now);
        courseForum.setDeletedFlag(GlobalDeletedFlag.NORMAL);
        MyModelUtil.setDefaultValue(courseForum, "pid", 0L);
        return courseForum;
    }

    private CourseForumFile buildDefaultValue(CourseForumFile courseForumFile) {
        TokenData tokenData = TokenData.takeFromRequest();
        courseForumFile.setCreateUserId(tokenData.getUserId());
        courseForumFile.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        courseForumFile.setCreateTime(now);
        courseForumFile.setUpdateTime(now);
        return courseForumFile;
    }

    @Override
    public List<CourseForum> getAllCourseForumList() {
        TokenData tokenData = TokenData.takeFromRequest();
        return courseForumMapper.getAllCourseForumList(tokenData.getUserId());
    }

    @Override
    public CourseForum getCourseForumById(Long id) {
        TokenData tokenData = TokenData.takeFromRequest();
        return courseForumMapper.getCourseForumById(id, tokenData.getUserId());
    }
}
